#!/bin/bash
echo "start startup"
port_list=(5000 5001)
pro_path="/leadbank/jenkins_tool/app.py"
log_path="/leadbank/jenkins_tool/log4py/access.log"
pid_path="/leadbank/jenkins_tool/pid/"
pro_name="app"
env="prod"

RETVAL=0

start() {
  for i in ${port_list[*]}; do
    echo "in loop ${i}"
    p=$(/usr/sbin/lsof -i :${i} | wc -l)

    echo "${p}"
    if [ ${p} -ge 2 ]; then
      echo "${pro_name} ${i} already exists !"
    else
      echo "in python"
      PIDFILE=${pid_path}${pro_name}"_"${i}".pid"
      echo ${PIDFILE}
      nohup python ${pro_path} ${i} ${env} &>>${log_path} 2>&1 &
      echo $! >${PIDFILE}
      #python ${pro_path} ${i} &>> ${log_path}
      RETVAL=$?
      if [ ${RETVAL} == 0 ]; then
        echo "${pro_name} ${i} started"

      else
        echo "${pro_name} ${i} dose not start ..."
      fi

    fi
  done
  return $RETVAL
}
stop() {
  for i in ${port_list[*]}; do
    pidfile="${pid_path}/${pro_name}_${i}.pid"
    if [ -f ${pidfile} ]; then
      pid=$(cat ${pidfile})
      kill -9 ${pid}
      RETVAL=$?
      if [ ${RETVAL} == 0 ]; then
        echo "${pro_name} ${i} stop ..."
      else
        echo "${pro_name} ${i} stop ..."
      fi
      rm -f ${pidfile}
    else
      echo "${pro_name} ${i} Has stopped !"
    fi
  done
}
# See how we were called.
case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
*)
  echo $"Usage: $prog {start|stop|}"
  RETVAL=2
  ;;
esac
exit $RETVAL
